<route lang="json5">
  {
    style: {
      navigationStyle: 'custom',
      navigationBarTitleText: '完善信息',
    },
  }
</route>
  
<template>
  <view class="bg-white" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
    <wd-form ref="formRefs" :model="formData" :errorType="errorType"
      v-if="hasDictInfo"
    >
      <view class="w-750rpx m-a">
        <view class="w-center pt-22rpx pb-22rpx flex-sb-center">
          <view class="font-size-28rpx">
            <text class="font-size-15px color-#fa4350">*</text>
            性别
          </view>
          <wd-radio-group v-model="formData.gender" inline shape="dot">
            <wd-radio value="0">男</wd-radio>
            <wd-radio value="1">女</wd-radio>
          </wd-radio-group>
        </view>
        <view class="border-1px"></view>
      </view>
      
      <wd-datetime-picker 
        label="出生年月" 
        align-right 
        prop="birthYearMonth"
        type="date"
        :minDate="-662688000000"
        v-model="formData.birthYearMonth" 
        :rules="[{ required: true, message: '请选择出生年月！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-cell 
        title="行业/职业" 
        required 
        :value="professionName ? professionName : '请选择'"
        :custom-value-class="professionName ? '' : 'cell-placeholder'"
        is-link 
        :to="'/feature/school?type=profession&typeCode=' + formData.profession"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-cell 
        title="身高体重" 
        required 
        :value="`
          ${ user.activityHeightInfo.height ? user.activityHeightInfo.height + 'cm' : '请选择' }/
          ${ user.activityHeightInfo.weight ? user.activityHeightInfo.weight + 'kg' : '请选择' }
        `" 
        is-link 
        to="/feature/weight?type=activityHeightInfo"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['income']" 
        label="年收入" 
        v-model="formData.incomeStatus" 
        prop="incomeStatus"
        :rules="[{ required: true, message: '请选择年收入！' }]"
      />
      <view class="border-1px"></view>

      <wd-cell 
        title="居住地" 
        required 
        :value="city ? city : '请选择'" 
        :custom-value-class="city ? '' : 'cell-placeholder'"
        is-link 
        :to="`/feature/areaPicker?isAll=1&isRequired=1&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>
    </wd-form>

    <view class="flex-center py-100rpx" v-else>
      <wd-loading />
    </view>
    
    <!-- 实名认证 -->
    <real-name />
    
    <!-- 协议 -->
    <view class="w-center !mt-112rpx font-size-24rpx flex-a-center">
      <wd-checkbox v-model="checked">
        <wd-text text="我已阅读并同意" color="#323233"></wd-text>
      </wd-checkbox>
      <wd-text text="《用户协议》" color="#165DFF" @click="toPath('/feature/richtext?code=5')"></wd-text>
      <wd-text text="和" color="#323233"></wd-text>
      <wd-text text="《隐私政策》" color="#165DFF" @click="toPath('/feature/richtext?code=2')"></wd-text>
    </view>

    <!-- 保存按钮 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="loading"
        @click="submit"
      >保存</wd-button>
    </view>

    <view class="w-full h-78rpx"></view>
  </view>
</template>
  
<script lang="ts" setup>
import RealName from "@/components/real-name.vue";
import { AddUserActivityInfo } from '@/service/db_activity';
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { formatDate } from '@/utils';
import { useMessage, useToast } from 'wot-design-uni';

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();

const checked = ref(false);
const formData = reactive({
  gender: '0', // 性别(0：男，1：女)
  profession: '', // 从事行业/职业
  incomeStatus: '', // 收入情况
  height: 0, // 身高 (单位: cm)
  weight: 0, // 体重 (单位: kg)
  birthYearMonth: +new Date('1995-01-01'), // 出生年月
  provinceId: '',
  cityId: '',
  districtId: '',
})

const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const submit = () => {
  if (!checked.value) return toast.show('请先阅读协议！');
  if (!formData.profession) return toast.show('请选择行业/职业！');
  if (!formData.provinceId) return toast.show('请选择居住所在地！');
  if (!user.userInfo.verificationFlag) return toast.show('请实名认证后再保存征婚资料');
  formData.height = user.activityHeightInfo.height;
  formData.weight = user.activityHeightInfo.weight;
  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;
      
      user.loginSubmit = true;
      const data = {
        ...formData,
        userId: user.userInfo.id,
        birthYearMonth: formatDate(new Date(formData.birthYearMonth), 'YYYY-MM-DD'),
      }
      addUserActivityInfo(data);
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

const loading = ref(false);
const message = useMessage();
// 补充信息
const addUserActivityInfo = async(data) => {
  try {
    loading.value = true;
    const res = await AddUserActivityInfo(data);
    loading.value = false;
    if (res.code != 200) {
      return toast.show(res.message);
    }
    toast.show('保存成功!');
    user.getUserInfo();

    if (isChatType.value) {
      message.alert('会员私信免费，非会员按三大运营商正规标准资费');
      return
    }
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
  } catch (error) {
    loading.value = false;
    console.log(error)
  }
}

const backfill = () => {
  const _userProfileInfoVo = user.userInfo.userProfileInfoVo || {};
  const { provinceId } = user.activityInfo || {};
  const data: any = provinceId ? user.activityInfo : _userProfileInfoVo;
  if (!data.provinceId) return;
  for (const key in formData) {
    if (['birthYearMonth'].includes(key)) {
      formData[key] = +new Date(data[key]);
      continue;
    }
    formData[key] = data[key];
  }
  
  user.activityHeightInfo.height = data.height;
  user.activityHeightInfo.weight = data.weight;

  professionName.value = getTypeName(data.profession);
  const { provinceName, cityName, districtName } = data || {};
  city.value = provinceName === cityName ? `${cityName}${districtName}` : `${provinceName}${cityName}${districtName}`;
}

const toPath = (path) => {
  uni.navigateTo({ url: path })
}

const getTypeName = (typeCode, name = 'profession') => {
  const list = useCommon.commonState.dictInfo[name] || [];
  const item = list.find(item => item.typeCode === typeCode) || { typeName: '' };
  return item.typeName || ''
}

const hasDictInfo = computed(() => {
  return useCommon.commonState.dictInfo && JSON.stringify(useCommon.commonState.dictInfo) !== '{}';
})

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

const professionName = ref('');
// 更新学校/行业
function handleUpdateSchool(_data) {
  if (!_data) return;
  const { type, data } = JSON.parse(_data);
  formData[type] = data.typeCode || '';
  professionName.value = data.typeName || '';
}

const titleType = ref(0);
const isChatType = ref(0); // 是否从私聊进来，是为1 否为0
const list = ['完善信息', '完善发布者信息', '完善应约者信息']
onLoad((options) => {
  const { type, isChat } = options;
  isChatType.value = isChat;
  titleType.value = type ? Number(type) : 0;
  uni.$on('updateArea', handleUpdateArea);
  uni.$on('updateSchool', handleUpdateSchool);
  user.getUserActivityInfo(() => {
    backfill();
  })
  
  // #ifdef H5
  setTimeout(() => {
    document.title = list[titleType.value];
  }, 0)
  // #endif
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
  uni.$off('updateSchool', handleUpdateSchool);
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = list[titleType.value];
  })
  if (!user.userInfo.id) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return
  }
})
</script>

<style lang="scss" scoped>
:root,
page {
  background-color: #fff !important;
}

.textarea-com {
  font-size: 28rpx !important;
  box-sizing: border-box !important;
}

:deep(.uni-textarea-textarea) {
  @extend .textarea-com;
}

:deep(.wot-theme-light) {
  .wd-textarea__inner,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    @extend .textarea-com;
    background-color: #FAF7FF !important;
  }

  .wd-textarea {
    background-color: #FAF7FF !important;
  }
}

:deep(.wot-theme-dark) {
  .wd-textarea,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    background-color: #141414 !important;
  }
}

:deep(.wd-input) {
  padding-right: 44rpx !important;
}

// 覆盖 wd-slider 样式 start
:deep(.wd-slider__label),
:deep(.wd-slider__label-min),
:deep(.wd-slider__label-max) {
  display: none
}
:deep(.wd-slider) {
  padding-top: 26rpx;

  .wd-slider__button {
    border: 3rpx solid #986DF0;
  }
}
// 覆盖 wd-slider 样式 end

:deep(.wd-checkbox) {
  .wd-checkbox__shape {
    border-width: 1px;
  }
  .wd-checkbox__txt {
    font-size: 24rpx;
  }
  .wd-checkbox__label {
    margin-left: 6rpx;
  }
}
</style>
    